package org.siteanalyser.service.impl;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.siteanalyser.domain.FbResponse;
import org.siteanalyser.domain.Message;
import org.siteanalyser.service.Service;
import org.siteanalyser.service.SystemException;
import org.springframework.beans.factory.annotation.Required;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class FbSharesServiceImpl implements Service {
    private String baseUrl;

    public void process(final Message message) throws SystemException {
        makeRequest(message);
    }

    private void makeRequest(final Message message) {
        final String siteNameToCheck = message.getRequest().getUrl();
        Document doc = null;
        try {
            doc = Jsoup.connect(baseUrl+siteNameToCheck).get();
        } catch (final IOException e) {
        	// fb shares site not accessible
            throw new SystemException(e.getMessage());
        }
        if (doc == null) {
            throw new SystemException(String.format("Unable to parse URL: %s", baseUrl+siteNameToCheck));
        }
        // at this moment we have fb shares response
        try {
        	String jsonString = doc.getElementsByTag("body").first().ownText();
        	final Gson gson = new Gson();
        	Type collectionType = new TypeToken<Map<String,FbResponse>>(){}.getType();
        	Map<String,FbResponse> shareData = gson.fromJson(jsonString, collectionType);
        	FbResponse res = shareData.get(siteNameToCheck);
        	message.getReport().addReportItem("fb.shares", res.getShares());
		} catch (Exception e) {
            throw new SystemException(e.getMessage());
		}
    }

    @Required
    public void setBaseUrl(final String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public String getBaseUrl() {
        return baseUrl;
    }
}
